package com.springframework.boot.shiro.config;


import com.springframework.boot.shiro.cache.RedisCacheManager;
import com.springframework.boot.shiro.realm.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * 用来整合shiro相关的配置
 */
@Configuration
public class ShiroConfig {
    //1、创建ShiroFilter

    /**
     * 负责拦截所有请求
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置系统的受限资源
        Map<String,String> map = new HashMap<>();


        map.put("/user/**","anon");//anon 设置公共资源
        map.put("/register.jsp","anon");//anon 设置公共资源
        map.put("/verifyCode/getVerify","anon");//anon 设置公共资源

        map.put("/**","authc");//authc 请求这个资源需要认证和授权

        shiroFilterFactoryBean.setLoginUrl("/login.jsp");//默认认证界面路径
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }
    //2.创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;

    }
    //3、创建自定义的realm
    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher =new HashedCredentialsMatcher();
        //设置加密算法为MD5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        //开启缓存管理
        customerRealm.setCacheManager(new EhCacheManager());//使用ehcache缓存
//        customerRealm.setCacheManager(new RedisCacheManager());//使用redis缓存
        customerRealm.setCachingEnabled(true);//开启全局缓存
        customerRealm.setAuthenticationCachingEnabled(true);//开启认证缓存
        customerRealm.setAuthenticationCacheName("authenticationCache");//设置认证缓存名称
        customerRealm.setAuthorizationCachingEnabled(true);//开启授权缓存
        customerRealm.setAuthenticationCacheName("authorizationCache");//设置授权缓存名称
        return customerRealm;
    }
}
